#include <A_Config.h>

static bool done = false;

static void kb_event_cb(lv_event_t *e)
{
    done = true;
}

int msgbox_number(const char *str, int max, int min, int value_pre)
{
    String res = String(value_pre);
    int ret = value_pre;
    LOCKLV();
    lv_obj_t *scr_msgbox = lv_obj_create(lv_layer_top());
    lv_obj_set_size(scr_msgbox, 200, 100);
    lv_obj_center(scr_msgbox);
    lv_obj_set_pos(scr_msgbox, 0, -70);
    lv_obj_pop_up(scr_msgbox, 30, 300, 0);

    lv_obj_t *lblInfo = lv_label_create(scr_msgbox);
    lv_label_set_text(lblInfo, str);
    lv_label_set_long_mode(lblInfo, LV_LABEL_LONG_SCROLL_CIRCULAR);
    lv_obj_set_style_text_font(lblInfo, &lv_font_chinese_16, 0);
    lv_obj_set_height(lblInfo, 22);
    lv_obj_set_width(lblInfo, lv_pct(100));
    lv_obj_align(lblInfo, LV_ALIGN_TOP_MID, 0, 0);
    lv_obj_set_style_text_align(lblInfo, LV_TEXT_ALIGN_CENTER, 0);
    lv_obj_set_style_pad_all(lblInfo, 0, 0);

    lv_obj_t *ta = lv_textarea_create(scr_msgbox);
    lv_obj_set_size(ta, lv_pct(90), lv_pct(50));
    lv_textarea_set_accepted_chars(ta, "-0123456789.");
    lv_textarea_set_one_line(ta, true);
    lv_textarea_set_text(ta, "");
    lv_obj_add_state(ta, LV_STATE_FOCUSED);
    lv_obj_align(ta, LV_ALIGN_BOTTOM_MID, 0, 0);

    /*Create a keyboard*/
    lv_obj_t *kb = lv_keyboard_create(lv_layer_top());
    lv_obj_set_size(kb, LV_HOR_RES, LV_VER_RES / 2);
    lv_keyboard_set_mode(kb, LV_KEYBOARD_MODE_NUMBER);
    lv_keyboard_set_textarea(kb, ta);
    lv_obj_pop_up(kb, 30, 300, 200);
    lv_obj_add_event_cb(kb, kb_event_cb, LV_EVENT_READY, NULL);
    UNLOCKLV();
start:
    done = false;
    while (done == false)
    {
        vTaskDelay(100);
    }
    res = String(lv_textarea_get_text(ta));
    ret = res.toInt();
    if(ret > max || ret < min)
    {
        msgbox(LV_SYMBOL_CLOSE " 错误", "输入数字超范围，请重新输入");
        goto start;
    }
    LOCKLV();
    lv_obj_fall_down(scr_msgbox);
    lv_obj_fall_down(kb, 30, 300, 200);
    UNLOCKLV();
    vTaskDelay(530);
    LOCKLV();
    lv_obj_del(scr_msgbox);
    lv_obj_del(kb);
    UNLOCKLV();
    return ret;
}
